package org.xbdframework.dao.core.sqlandparam.builder;

import java.util.*;

import org.apache.commons.lang3.ArrayUtils;

import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import org.xbdframework.dao.core.BasePo;
import org.xbdframework.dao.core.sqlandparam.AbstractSqlAndParamBuilder;
import org.xbdframework.jdbc.core.SqlAndParam;

public class InsertSqlAndParamBuilder<T extends BasePo>
		extends AbstractSqlAndParamBuilder<T> {

	public InsertSqlAndParamBuilder(T po) {
		super(po);
	}

	@Override
	public SqlAndParam<Object[]> buildArraySql() {
		Object[] parametersArray = new Object[0];

		StringBuilder sb = createPreInsertSql();

		for (int i = 0; i < this.setColumns.size(); ++i) {
			if (i > 0) {
				sb.append(", ");
			}

			sb.append("?");
			parametersArray = ArrayUtils.add(parametersArray, this.setValues.get(i));
		}

		sb.append(")");

		return new SqlAndParam<>(sb.toString(), parametersArray);
	}

	@Override
	public SqlAndParam<Object[]> buildArraySql(String where, Object[] paramArray) {
		throw new IllegalArgumentException("insert操作不支持此方法！");
	}

	@Override
	public SqlAndParam<Map<String, Object>> buildMapSql() {
		Map<String, Object> paramMap = new HashMap<>();

		StringBuilder sb = createPreInsertSql();

		for (int i = 0; i < this.setColumns.size(); ++i) {
			if (i > 0) {
				sb.append(", ");
			}

			sb.append(":").append(this.setColumns.get(i));
			paramMap.put(this.setColumns.get(i), this.setValues.get(i));
		}

		sb.append(")");

		return new SqlAndParam<>(sb.toString(), paramMap);
	}

	@Override
	public SqlAndParam<Map<String, Object>> buildMapSql(String where,
			Map<String, Object> paramMap) {
		throw new IllegalArgumentException("insert不支持此方法！");
	}

	@Override
	public SqlAndParam<SqlParameterSource> buildSqlParameterSourceSql() {
		StringBuilder sb = createPreInsertSql();

		for (int i = 0; i < this.setColumns.size(); ++i) {
			if (i > 0) {
				sb.append(", ");
			}

			sb.append(":").append(this.setColumns.get(i));
		}

		sb.append(")");

		return new SqlAndParam<>(sb.toString(),
				new BeanPropertySqlParameterSource(this.po));
	}

	@Override
	public SqlAndParam<SqlParameterSource> buildSqlParameterSourceSql(String where,
			SqlParameterSource params) {
		throw new IllegalArgumentException("insert不支持此方法！");
	}

	private StringBuilder createPreInsertSql() {
		StringBuilder sb = new StringBuilder();
		sb.append("insert into ").append(getTableName()).append(" (");

		for (int i = 0; i < this.setColumns.size(); ++i) {
			if (i > 0) {
				sb.append(", ");
			}

			sb.append(this.setColumns.get(i));
		}

		sb.append(") values (");

		return sb;
	}

}
